package com.yjd.pub.settlement.service;

import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.repayment.model.RepaymentClearModel;
import com.yjd.comm.repayment.service.IRepaymentClearService;
import com.yjd.comm.settlement.model.ClearDayDetailModel;
import com.yjd.comm.settlement.model.ClearDayMerchantModel;
import com.yjd.comm.settlement.service.IMerchantSettlementService;
import com.yjd.comm.util.ArithUtil;
import com.yjd.comm.util.DateUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.pub.settlement.dao.IClearDayDetailDao;
import com.yjd.pub.settlement.dao.IClearDayMerchantDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yangchangyan on 2017/8/24.
 */
@Service("merchantSettlementService")
public class MerchantSettlementService implements IMerchantSettlementService {

    @Override
    public void settlement(Long org_id, Long timeInSecond) throws Exception {

        // 时间格式：yyyyMMdd，如：20170824
        int clear_date = Integer.valueOf(DateUtil.format(new Date(timeInSecond*1000), DateUtil.PATTERN_yyyyMMdd));
        Long currentTime = FrameUtil.getTime(null);
        List<ClearDayDetailModel> merchantDailyDetails = clearDayDetailDao.getModelList(FrameUtil.newHashMap(
                "org_id", org_id, "clear_date", clear_date), true);

        Double trade_price = 0.0D;
        int trade_count = 0; // 成交笔数
        int refund_count = 0; // 退单笔数
        Double loan_price = 0.0D; // 收入金额
        Double borrow_price = 0.0D; // 支出金额
        for(ClearDayDetailModel cdm : merchantDailyDetails){
            // 借贷标志 1 收入 0 未知  -1 支出
            // type : 1 订单(平台转账给商户) 2 退单（商户退钱给平台）
            if(1==cdm.getType().intValue()){
                trade_count += 1;
                loan_price = ArithUtil.add(loan_price, cdm.getClear_price());
                trade_price = ArithUtil.add(trade_price,cdm.getOrder_price());
            }else if(2==cdm.getType().intValue()){
                refund_count += 1;
                borrow_price = ArithUtil.add(borrow_price, cdm.getClear_price());
            }
        }

        //查询日结还款报表记录
        List<RepaymentClearModel> repaymentClearModelList = repaymentClearService.getModelList(FrameUtil.newHashMap("org_id",org_id,"clear_date",clear_date),
                DbWREnums.READ);

        Double repayment_price = 0D;//用户还款金额
        Double interest_price = 0D;//利息金额
        Double manage = 0D;//利息平台管理金额
        Double overdue_price = 0D;//用户逾期利息
        Double manage_overdue = 0D;//用户逾期平台分成金额

        if(repaymentClearModelList!=null&&repaymentClearModelList.size()>0){
            for (RepaymentClearModel clearModel : repaymentClearModelList){
                repayment_price = ArithUtil.add(repayment_price,clearModel.getRepayment_price());
                interest_price = ArithUtil.add(interest_price,clearModel.getInterest_price());
                manage = ArithUtil.add(manage,clearModel.getManage());
                overdue_price = ArithUtil.add(overdue_price,clearModel.getOverdue_price());
                manage_overdue = ArithUtil.add(manage_overdue,clearModel.getManage_overdue());
            }
        }

        // 如果已经生成过了，则先删除商户结算单
        clearDayMerchantDao.deleteSettlementList(FrameUtil.newHashMap("org_id", org_id, "clear_date", clear_date), true);
        ClearDayMerchantModel cdmm = new ClearDayMerchantModel();
        cdmm.setClear_no("M" + org_id + "-" + clear_date);
        cdmm.setClear_date(Long.valueOf(clear_date));
        cdmm.setOrg_id(org_id);
        cdmm.setTrade_price(trade_price); // 成交额
        cdmm.setTrade_count(trade_count);
        cdmm.setRefund_count(refund_count);
        cdmm.setLoan_price(loan_price);
        cdmm.setBorrow_price(borrow_price);
        cdmm.setStatus(0); // 0 商户待确认收款   1商户已确认收款
        cdmm.setRepayment_price(repayment_price);//用户还款金额
        cdmm.setInterest_price(interest_price);//利息金额
        cdmm.setManage(manage);//利息平台管理金额
        cdmm.setOverdue_price(overdue_price);//用户逾期利息
        cdmm.setManage_overdue(manage_overdue);//用户逾期平台分成金额
        cdmm.setCreate_time(currentTime);
        cdmm.setUpdate_time(currentTime);
        clearDayMerchantDao.insertModel(cdmm, true);
    }

    @Override
    public void settlementAll(Long timeInSecond) throws Exception {
        // 查询所有商户id
        Set<Long> orgIds = organizationService.allOrgAndName().keySet();

        // 计算所有商户
        for(Long org_id : orgIds){
            this.settlement(org_id, timeInSecond);
        }
    }

    @Override
    public void settlementAll(Long org_id, Long startTime, Long endTime) throws Exception {
        Set<Long> orgIds = new HashSet<Long>();

        if(org_id == null || org_id == 0){
            // 查询所有商户id
            orgIds = organizationService.allOrgAndName().keySet();
        } else {
            orgIds.add(org_id);
        }

        // 循环生成结算单
        Long start = null;
        for(Long id : orgIds){
            start = startTime;
            for( ; start<= endTime ; ){
                this.settlement(id, start);
                // 下一天
                start += DateUtil.DAY_IN_SECOND;
            }
        }
    }

    @Resource
    private IClearDayDetailDao clearDayDetailDao;

    @Resource
    private IClearDayMerchantDao clearDayMerchantDao;

    @Resource
    private IRepaymentClearService repaymentClearService;

    @Resource
    private IOrganizationService organizationService;

}
